import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/vpn_provider.dart';
import '../models/server_config.dart';

/// 批量测速结果对话框
/// 显示测速进度、实时统计和测速结果
class BatchPingTestDialog extends StatefulWidget {
  final List<ServerConfig> servers;

  const BatchPingTestDialog({
    super.key,
    required this.servers,
  });

  @override
  State<BatchPingTestDialog> createState() => _BatchPingTestDialogState();
}

class _BatchPingTestDialogState extends State<BatchPingTestDialog> {
  int _testedCount = 0;
  int _successCount = 0;
  int _failedCount = 0;
  bool _isCompleted = false;
  final List<ServerConfig> _failedServers = [];
  ServerConfig? _currentTesting;

  @override
  void initState() {
    super.initState();
    _startBatchTest();
  }

  Future<void> _startBatchTest() async {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    
    for (var i = 0; i < widget.servers.length; i++) {
      final server = widget.servers[i];
      
      setState(() {
        _currentTesting = server;
      });
      
      // 测试单个服务器的Ping
      await vpnProvider.testPing(server);
      
      // 更新统计
      setState(() {
        _testedCount++;
        
        // 从provider获取更新后的服务器信息
        final updatedServer = vpnProvider.allServers.firstWhere(
          (s) => s.matchesServer(server),
          orElse: () => server,
        );
        
        if (updatedServer.ping >= 0 && updatedServer.ping < 10000) {
          _successCount++;
        } else {
          _failedCount++;
          _failedServers.add(updatedServer);
        }
      });
    }
    
    setState(() {
      _isCompleted = true;
      _currentTesting = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    final totalCount = widget.servers.length;
    final progress = totalCount > 0 ? _testedCount / totalCount : 0.0;

    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      child: Container(
        constraints: const BoxConstraints(
          maxWidth: 500,
          maxHeight: 600,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 头部
            Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Theme.of(context).colorScheme.primary,
                    Theme.of(context).colorScheme.primary.withOpacity(0.8),
                  ],
                ),
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(20),
                  topRight: Radius.circular(20),
                ),
              ),
              child: Row(
                children: [
                  Icon(
                    _isCompleted ? Icons.check_circle : Icons.speed,
                    color: Colors.white,
                    size: 28,
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      _isCompleted ? 'Test Completed' : 'Testing Servers',
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  if (!_isCompleted)
                    const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation(Colors.white),
                      ),
                    ),
                ],
              ),
            ),

            // 进度条
            if (!_isCompleted)
              LinearProgressIndicator(
                value: progress,
                backgroundColor: Colors.grey.shade200,
                valueColor: AlwaysStoppedAnimation(
                  Theme.of(context).colorScheme.primary,
                ),
              ),

            // 内容
            Flexible(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 总体统计
                    _buildStatisticsSection(totalCount),
                    
                    const SizedBox(height: 16),
                    
                    // 当前测试的服务器
                    if (_currentTesting != null)
                      _buildCurrentTestingSection(),
                    
                    // 测试完成后的详细信息
                    if (_isCompleted) ...[
                      const Divider(height: 32),
                      _buildCompletedSection(),
                    ],
                  ],
                ),
              ),
            ),

            // 底部按钮
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(20),
                  bottomRight: Radius.circular(20),
                ),
              ),
              child: _buildActionButtons(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatisticsSection(int totalCount) {
    return Row(
      children: [
        Expanded(
          child: _buildStatCard(
            'Total',
            totalCount.toString(),
            Icons.dns,
            Colors.blue,
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: _buildStatCard(
            'Tested',
            '$_testedCount/$totalCount',
            Icons.task_alt,
            Colors.orange,
          ),
        ),
      ],
    );
  }

  Widget _buildStatCard(String label, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 28),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey.shade600,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCurrentTestingSection() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Theme.of(context).brightness == Brightness.dark
            ? Colors.blue.shade900.withOpacity(0.2)
            : Colors.blue.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: Theme.of(context).brightness == Brightness.dark
              ? Colors.blue.shade700.withOpacity(0.5)
              : Colors.blue.shade200,
        ),
      ),
      child: Row(
        children: [
          const SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(strokeWidth: 2),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Testing...',
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  _currentTesting!.name,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                if (_currentTesting!.group != null) ...[
                  const SizedBox(height: 2),
                  Text(
                    'Group: ${_currentTesting!.group}',
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCompletedSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          'Test Results',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        
        // 成功和失败统计
        Row(
          children: [
            Expanded(
              child: _buildResultCard(
                'Success',
                _successCount.toString(),
                Icons.check_circle,
                Colors.green,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildResultCard(
                'Failed',
                _failedCount.toString(),
                Icons.error,
                Colors.red,
              ),
            ),
          ],
        ),
        
        // 失败的服务器列表
        if (_failedServers.isNotEmpty) ...[
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Theme.of(context).brightness == Brightness.dark
                  ? Colors.red.shade900.withOpacity(0.2)
                  : Colors.red.shade50,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.red.shade700.withOpacity(0.5)
                    : Colors.red.shade200,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(Icons.warning_amber_rounded, 
                         color: Colors.red.shade700, size: 20),
                    const SizedBox(width: 8),
                    Text(
                      'Failed Servers (${_failedServers.length})',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: Theme.of(context).brightness == Brightness.dark
                            ? Colors.red.shade300
                            : Colors.red.shade900,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                ..._failedServers.take(5).map((server) => Padding(
                  padding: const EdgeInsets.only(bottom: 4),
                  child: Row(
                    children: [
                      Icon(Icons.circle, size: 6, 
                           color: Colors.red.shade700),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          server.name,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.red.shade900,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                )),
                if (_failedServers.length > 5)
                  Padding(
                    padding: const EdgeInsets.only(top: 4),
                    child: Text(
                      'and ${_failedServers.length - 5} more...',
                      style: TextStyle(
                        fontSize: 11,
                        color: Colors.red.shade700,
                        fontStyle: FontStyle.italic,
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildResultCard(String label, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(icon, color: color, size: 24),
          const SizedBox(width: 8),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                value,
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: color,
                ),
              ),
              Text(
                label,
                style: TextStyle(
                  fontSize: 11,
                  color: Colors.grey.shade600,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons() {
    if (!_isCompleted) {
      return SizedBox(
        width: double.infinity,
        child: OutlinedButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Cancel'),
        ),
      );
    }

    return Row(
      children: [
        if (_failedServers.isNotEmpty)
          Expanded(
            child: OutlinedButton.icon(
              onPressed: () {
                _confirmDeleteFailedServers();
              },
              icon: const Icon(Icons.delete_sweep),
              label: const Text('Delete Failed'),
              style: OutlinedButton.styleFrom(
                foregroundColor: Colors.red,
                side: const BorderSide(color: Colors.red),
              ),
            ),
          ),
        if (_failedServers.isNotEmpty)
          const SizedBox(width: 12),
        Expanded(
          child: ElevatedButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Done'),
          ),
        ),
      ],
    );
  }

  void _confirmDeleteFailedServers() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.delete_sweep, color: Colors.red.shade700, size: 28),
            const SizedBox(width: 12),
            const Text('Delete Failed Servers?'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Delete all ${_failedServers.length} failed server${_failedServers.length > 1 ? 's' : ''}?',
              style: const TextStyle(fontSize: 15),
            ),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.orange.shade900.withOpacity(0.2)
                    : Colors.orange.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.orange.shade700.withOpacity(0.5)
                      : Colors.orange.shade200,
                ),
              ),
              child: Row(
                children: [
                  Icon(Icons.info_outline, 
                       color: Colors.orange.shade700, size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'This action cannot be undone. Failed servers will be permanently removed.',
                      style: TextStyle(
                        fontSize: 12,
                        color: Theme.of(context).brightness == Brightness.dark
                            ? Colors.orange.shade300
                            : Colors.orange.shade900,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton.icon(
            onPressed: () {
              _deleteFailedServers();
              Navigator.pop(context); // 关闭确认对话框
              Navigator.pop(context); // 关闭测速结果对话框
            },
            icon: const Icon(Icons.delete_sweep),
            label: const Text('Delete All Failed'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  void _deleteFailedServers() {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    
    int deletedCount = 0;
    for (var server in _failedServers) {
      // 检查是否是正在连接的服务器
      final isConnected = vpnProvider.status == VpnStatus.connected &&
                         server.matchesServer(vpnProvider.currentServer);
      
      if (!isConnected) {
        vpnProvider.deleteServer(server.id);
        deletedCount++;
      }
    }
    
    // 显示删除结果
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const Icon(Icons.check_circle, color: Colors.white),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                deletedCount == _failedServers.length
                    ? 'Deleted $deletedCount failed server${deletedCount > 1 ? 's' : ''}'
                    : 'Deleted $deletedCount of ${_failedServers.length} failed servers (${_failedServers.length - deletedCount} skipped)',
              ),
            ),
          ],
        ),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 3),
      ),
    );
  }
}
